package com.luke.dubbo.user.service.impl;

import com.luke.dubbo.api.service.CallbackListener;
import com.luke.dubbo.api.service.CallbackService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Descrtption CallbackServiceImpl
 * @Author luke
 * @Date 2020/3/31
 **/
public class CallbackServiceImpl implements CallbackService {

    private final Map<String, List<CallbackListener>> listeners = new ConcurrentHashMap<>();

    public CallbackServiceImpl() {
        Thread t = new Thread(() ->{
            while(true) {
                try {
                    System.out.println("listeners:"+listeners);
                    for(Map.Entry<String, List<CallbackListener>> entry : listeners.entrySet()){
                        try {
                            List<CallbackListener> callbackListeners = entry.getValue();
                            callbackListeners.forEach((callbackListener) -> {
                                callbackListener.changed(getChanged(entry.getKey()));
                            });
                        } catch (Throwable t1) {
                            listeners.remove(entry.getKey());
                        }
                    }
                    Thread.sleep(5000); // 定时触发变更通知
                } catch (Throwable t2) { // 防御容错
                    t2.printStackTrace();
                }
            }
        });
        t.setDaemon(true);
        t.start();
    }

    @Override
    public void addListener(String key, CallbackListener listener) {
        System.out.println("---addListener,key:"+key+",listener:"+listener);
        if(listeners.containsKey(key)){
            listeners.get(key).add(listener);
        }else{
            List<CallbackListener> list = new ArrayList<CallbackListener>();
            list.add(listener);
            listeners.put(key, list);
            //listener.changed(getChanged(key)); // 发送变更通知
        }
    }

    private String getChanged(String key) {
        return "Changed: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

}
